//
//  ViewController.swift
//  Swift-TableView-Example
//
//  Created by Bilal ARSLAN on 11/10/14.
//  Copyright (c) 2014 Bilal ARSLAN. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import KeychainSwift

//设置回调函数
func swiftCallBackVoid_main( p: UnsafeMutablePointer<APIStruct> )
{
    
    //let _locMS:MyStruct = (UnsafeMutablePointer<MyStruct>(p)).memory;
    
    print(p[0].num1)
    print(p[0].testNumber)
    
    
    let str = String(CString: UnsafePointer<CChar>(p[0].testNumber), encoding: NSUTF8StringEncoding)
    
    
    print(str)
    
    NSNotificationCenter.defaultCenter().postNotificationName("gameOverNotification", object: str)
}

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet var tableView: UITableView?
    //var eHttp:HTTPController = HTTPController()
    
    var recipes = [Recipe]()
     var tableData:[JSON]=[]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBarController!.tabBar.hidden = false;
        //self.navigationController?.navigationBarHidden = false;

        // Do any additional setup after loading the view, typically from a nib.
        tableView?.dataSource = self;
        tableView?.delegate = self;
        
        navigationItem.title = "首页"

        
        
        //eHttp.delegate = self
        
        //获取频道
        //eHttp.onsearch("http://42.62.18.210:8090/apiradio/ar/getListForFirstPage")
        //直接进行请求
        Alamofire.request(.GET, "http://42.62.18.210:8090/apiradio/ar/getListForFirstPage")
            .responseJSON { response in
                if let result = response.result.value {
                    let json = JSON(result)
                    
                    if let channels = json["obj"].array {
                        
                        print(channels)
                        self.tableData = channels
                        //print(tableData.count)
                        
                        for var i = 0; i < self.tableData.count; i++
                        {
                            let rowData:JSON = self.tableData[i]
                            // print(rowData["channelName"].string)
                            
                            self.recipes.append(Recipe(channelID: String(rowData["channelID"]), englishName: rowData["englishName"].string!, channelTopic: rowData["channelTopic"].string!, channelName: rowData["channelName"].string!))
                        }
                        
                        self.tableView!.reloadData()
                    }
                }else {
                    //为空
                    //print("kongkongkong")
                    self.noticeError("数据有误", autoClear: true, autoClearTime: 1)
                }
        }
        
        //initializeTheRecipes()
    
        //取出UUID,并且进行请求并且服务器端返回UUID
        let keychain = KeychainSwift(keyPrefix: "myTestKey_")
        print(keychain.get("QCDTUUID"))
        print(keychain.get("QCDTSEVERUUID"))
        print(keychain.get("QCDTPERTOPIC"))
        
        if(keychain.get("QCDTSEVERUUID") != nil) {
            //连接通信服务器
            dispatch_async(dispatch_get_global_queue(0, 0), {
                // something
                print("连接服务器")
                self.subConnectAndSubCribe()
            });
            
            dispatch_async(dispatch_get_global_queue(0, 0), {
                // something
                sleep(1)
                print("订阅回调函数")
                set_sub_callback(swiftCallBackVoid)
            });
            

        }else {
        
            let urladdress = "http://42.62.18.210:8090/apiradio/ar/autoRegister?deviceCode="+keychain.get("QCDTUUID")!+"&deviceType=iphone"
            print(urladdress)
            Alamofire.request(.GET, urladdress)
                .responseJSON { response in
                    
                    if let result = response.result.value {
                        //print("JSON: \(JSON)")
                        let json = JSON(result)
                        let deviceID = json["obj"]["deviceID"]
                        let personTopic = json["obj"]["personTopic"]
                        print(deviceID)
                        print(personTopic)
                        
                        keychain.set(String(deviceID), forKey: "QCDTSEVERUUID")
                        keychain.set(String(personTopic), forKey: "QCDTPERTOPIC")
                        
                        //连接通信服务器
                        dispatch_async(dispatch_get_global_queue(0, 0), {
                            // something
                            
                            self.subConnectAndSubCribe()
                            //在这里使用C函数的，设置相应的回调函数
                            //set_sub_callback(swiftCallBackVoid_main)
                            //set_sub_callback(swiftCallBackVoid)
                        });
                        
                    }
            }
        }
        
        //路况终端注册服务
        if(keychain.get("QCDTTRAFFICID") != nil) {
            
        }else {
            let urladdress = "http://cloud.palmgo.cn/tc/register/userregister.service?app_key=26198e8c4c2945158f86d0608f7ee923&imsi="+keychain.get("QCDTUUID")!+"&format=json"
            print(urladdress)
            Alamofire.request(.GET, urladdress)
                .responseJSON { response in
                    if let result = response.result.value {
                        print("JSON: \(result)")
                        let json = JSON(result)
                        let deviceID = json["license"]
                        keychain.set(String(deviceID), forKey: "QCDTTRAFFICID")
                    }
            }
        }
    }
    
    
    //在这进行调用sub连接并且进行订阅, 在这里开线程
    func subConnectAndSubCribe() ->Int {
        let keychain = KeychainSwift(keyPrefix: "myTestKey_")
        let userUUID =  keychain.get("QCDTSEVERUUID")
        var PerSonTopic:String?
        if keychain.get("personTopic") != nil {
            PerSonTopic = keychain.get("personTopic")
        }else {
            PerSonTopic = keychain.get("QCDTPERTOPIC")
        }
        
        //
        var sub_object = carRadio_sub()
        
        let unsafePointerOfN1 = (userUUID! as NSString).UTF8String
        sub_object.uuid = UnsafeMutablePointer(unsafePointerOfN1)
        sub_object.client_type = 2;
        
        let unsafePointerOfN2 = ("123.56.93.31" as NSString).UTF8String
        sub_object.server_ip = UnsafeMutablePointer(unsafePointerOfN2)
        sub_object.server_port = 1883;
        sub_object.keepalive = 30;
        sub_object.clean_session = false;
        sub_object.quiet = false;
        let unsafePointerOfN3 = ("/USER" as NSString).UTF8String
        sub_object.file_path = UnsafeMutablePointer(unsafePointerOfN3)
        sub_object.product_type = 1;
        let unsafePointerOfN4 = ("123" as NSString).UTF8String
        sub_object.product_id = UnsafeMutablePointer(unsafePointerOfN4)
        

        sub_object.qos = 1;
        
        //sprintf(sub_object.topics[0], "1/2/3");
        //let unsafePointerOfN = ("1123" as NSString).UTF8String
        //sub_object.topics[0] = UnsafeMutablePointer(unsafePointerOfN)
        //sub_object.topic_num = 1;

        //let keychain = KeychainSwift(keyPrefix: "myTestKey_")
        //let word = keychain.get("QCDTPERTOPIC")
        let unsafePointerOfN5 = ("public/1" as NSString).UTF8String
        sub_object.person_topic = UnsafeMutablePointer(unsafePointerOfN5)
        
        let unsafePointerOfN6 = (PerSonTopic! as NSString).UTF8String
        sub_object.sys_topic = UnsafeMutablePointer(unsafePointerOfN6)
        
        
       // sub_object.topics
        sub_init_connect(sub_object);
    
        return 0;
    }
    
    
    // MARK: - UITableView DataSource Methods
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifier: String = "tableCell"
        
        var cell: TableCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? TableCell
        
        //消除前面的15px
        //cell.separatorInset = UIEdgeInsetsZero
        
        if cell == nil {
            cell = TableCell(style: UITableViewCellStyle.Value1, reuseIdentifier: identifier)
        }
        
        cell.configurateTheCell(recipes[indexPath.row])
        
        return cell!
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return recipes.count
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 78.0
    }
    
/*
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if editingStyle == UITableViewCellEditingStyle.Delete {
            recipes.removeAtIndex(indexPath.row)
            self.tableView?.reloadData()
            self.tableView?.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Top)
            
        }
    }
  */
    //MARK: - UITableView Delegate Method
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    
    /* 获取数据的回调函数 */
    func didRecieveResults(results: AnyObject) {
        
        let getString:String = results as! String
        print(getString)
        if getString == "error" {
            //说明服务器出错
            self.noticeError("数据有误", autoClear: true, autoClearTime: 2)
            return
        }
        //print("results: \(results)")
        let json = JSON(results)

        if let channels = json["obj"].array {
            
            print(channels)
            tableData = channels
            //print(tableData.count)

            for var i = 0; i < tableData.count; i++
            {
                let rowData:JSON = tableData[i]
               // print(rowData["channelName"].string)
                
                recipes.append(Recipe(channelID: String(rowData["channelID"]), englishName: rowData["englishName"].string!, channelTopic: rowData["channelTopic"].string!, channelName: rowData["channelName"].string!))
            }
            
            self.tableView!.reloadData()
        }
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "recipeDetail" {
            let indexPath = self.tableView!.indexPathForSelectedRow
            let destinationViewController: DetailViewController = segue.destinationViewController as! DetailViewController
            
            destinationViewController.prepString = recipes[indexPath!.row].channelName
            destinationViewController.nameString = recipes[indexPath!.row].englishName
            destinationViewController.channelIDInt = recipes[indexPath!.row].channelID
            destinationViewController.channelTopic = recipes[indexPath!.row].channelTopic
            //destinationViewController.imageName = recipes[indexPath!.row].thumbnails
        }
    }
}
